package edu.cth.speedapp;

import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.provider.Settings;
import android.util.Log;
import android.widget.FrameLayout;
import net.sourceforge.zbar.Config;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;


public abstract class ScannerActivity extends NFCActivity {

	
	//Barcode processor
    private ImageScanner scanner;
    
    private Camera mCamera;
    private CameraPreview mPreview;
    private Handler autoFocusHandler;
    
   
    private MediaPlayer qrSound;
    
    private Vibrator vibrator;
    
    private boolean qrActive;
    
    static {
        System.loadLibrary("iconv");
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    	
    	// Instance barcode scanner //
        scanner = new ImageScanner();
        scanner.setConfig(0, Config.X_DENSITY, 3);
        scanner.setConfig(0, Config.Y_DENSITY, 3);
        
        autoFocusHandler = new Handler();
        
        //Sound on scanning a qr code
        qrSound = MediaPlayer.create(this, Settings.System.DEFAULT_NOTIFICATION_URI);
        OnCompletionListener ocl = new OnCompletionListener() {
			
			public void onCompletion(MediaPlayer mp) {
				return;
			}
		};
        qrSound.setOnCompletionListener(ocl);
        
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        
        
    }
    @Override
    protected void onResume() {
    	Log.d("lol", "mytag: onresume");
    	super.onResume();
    	mCamera = getCameraInstance();
    }
    
    @Override
    public void onPause() {
    	Log.d("lol", "mytag: onpause");
        super.onPause();  
        stopPreview();
        releaseCamera();
    }
    
    
    
    
    /** A safe way to get an instance of the Camera object. */
	public static Camera getCameraInstance(){
        Camera c = null;
       try{
        c = Camera.open();
      }catch(Exception e){
    	  
      }
        return c;
    }
	 protected void releaseCamera() {
	    	if(mPreview != null){
	        	mPreview.onRelease();
	        }
	        if (mCamera != null) {
	            
	            mCamera.setPreviewCallback(null);
	            mCamera.release();
	            mCamera = null;
	            
	        }
	    }
    
	protected void stopPreview() {
		if(mCamera != null){
	       mCamera.setPreviewCallback(null);
	       mCamera.stopPreview();
		}
		if(mPreview != null){
			mPreview.onRelease();
			mPreview = null; //TODO maybe unnecessary
		}
		
	}
	
	protected void startPreview(){
		//Toast.makeText(this, "start preview", Toast.LENGTH_SHORT).show();
		mCamera.setPreviewCallback(previewCallback);
        mCamera.startPreview();
        mCamera.autoFocus(autoFocusCallback);
		mPreview = new CameraPreview(this, mCamera, previewCallback, autoFocusCallback);
        FrameLayout preview = getPreviewContainer();
        preview.removeAllViews();
        preview.addView(mPreview);
        
	}
	
	public abstract FrameLayout getPreviewContainer();
	
	PreviewCallback previewCallback = new PreviewCallback() {   	
    	
		public void onPreviewFrame(byte[] data, Camera camera) {
	        Camera.Parameters parameters = camera.getParameters();
	        Size size = parameters.getPreviewSize();
	
	        Image barcode = new Image(size.width, size.height, "Y800");
	        barcode.setData(data);
	
	        int result = scanner.scanImage(barcode);
	        
	        if (result != 0) {
	        	stopPreview();
	           
	            
	            SymbolSet syms = scanner.getResults();
	            for (Symbol sym : syms) {
	            	qrRead(sym.getData());
	                
	            }
	        }
	    }
	
    };	
    
    AutoFocusCallback autoFocusCallback = new AutoFocusCallback() {
        public void onAutoFocus(boolean success, Camera camera) {
            autoFocusHandler.postDelayed(doAutoFocus, 1000);
        }
    };
    
    private Runnable doAutoFocus = new Runnable() {
        public void run() {
            if (mCamera != null)
                mCamera.autoFocus(autoFocusCallback);
        }
    };
    
    
	@Override
	public void tagRead(Tag tag) {
		Log.d("lol", "mytag: tag found");
		stopPreview();
		foundCode(bytesToHex(tag.getId()));
		
	}

	public void qrRead(String data){
		qrSound.start();
		foundCode(data);

	}
	
	protected void foundCode(String data){
		int awwwYeah = 300;
		vibrator.vibrate(awwwYeah);
	}

    
}
